package com.medical.literature.document.controller;

import com.medical.literature.common.vo.PageResult;
import com.medical.literature.common.vo.Result;
import com.medical.literature.document.dto.LiteratureQueryRequest;
import com.medical.literature.document.dto.LiteratureResponse;
import com.medical.literature.document.dto.LiteratureUploadFormData;
import com.medical.literature.document.entity.Literature;
import com.medical.literature.document.service.LiteratureService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 文献管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/literature")
@RequiredArgsConstructor
public class LiteratureController {
    
    private final LiteratureService literatureService;

    /**
     * 上传文献 - 使用@RequestParam方式处理multipart/form-data请求
     */
    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    public Result<Long> uploadLiterature(
            @Valid @RequestParam("file") MultipartFile file,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "authors", required = false) String authors,
            @RequestParam(value = "abstractText", required = false) String abstractText,
            @RequestParam(value = "keywords", required = false) String keywords,
            @RequestParam(value = "journal", required = false) String journal,
            @RequestParam(value = "publicationDate", required = false) String publicationDate,
            @RequestParam(value = "doi", required = false) String doi,
            @RequestHeader("X-User-Id") Long userId,
            @RequestHeader("X-User-Type") Integer userType) {
        
        // 构造LiteratureUploadFormData对象
        LiteratureUploadFormData request = new LiteratureUploadFormData();
        request.setFile(file);
        request.setTitle(title);
        request.setAuthors(authors);
        request.setAbstractText(abstractText);
        request.setKeywords(keywords);
        request.setJournal(journal);
        request.setPublicationDate(publicationDate);
        request.setDoi(doi);
        
        Long literatureId = literatureService.uploadLiteratureFormData(request, userId, userType);
        return Result.success("文献上传成功", literatureId);
    }

    /**
     * 分页查询文献列表
     */
    @PostMapping("/list")
    public Result<PageResult<LiteratureResponse>> getLiteratureList(@Valid @RequestBody LiteratureQueryRequest query,
                                                                   @RequestHeader("X-User-Id") Long userId) {
        PageResult<LiteratureResponse> result = literatureService.getLiteratureList(query, userId);
        return Result.success(result);
    }

    /**
     * 获取文献详情
     */
    @GetMapping("/{id}")
    public Result<LiteratureResponse> getLiteratureById(@PathVariable Long id,
                                                       @RequestHeader("X-User-Id") Long userId) {
        LiteratureResponse response = literatureService.getLiteratureById(id, userId);
        return Result.success(response);
    }

    /**
     * 更新文献信息
     */
    @PutMapping("/{id}")
    public Result<Void> updateLiterature(@PathVariable Long id,
                                        @Valid @RequestBody Literature literature,
                                        @RequestHeader("X-User-Id") Long userId) {
        literatureService.updateLiterature(id, literature, userId);
        return Result.success();
    }

    /**
     * 删除文献
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteLiterature(@PathVariable Long id,
                                        @RequestHeader("X-User-Id") Long userId) {
        literatureService.deleteLiterature(id, userId);
        return Result.success();
    }

    /**
     * 下载文献文件
     */
    @GetMapping("/{id}/download")
    public void downloadLiterature(@PathVariable Long id,
                                  @RequestHeader("X-User-Id") Long userId,
                                  HttpServletResponse response) {
        literatureService.downloadLiterature(id, userId, response);
    }

    /**
     * 收藏/取消收藏文献
     */
    @PostMapping("/{id}/favorite")
    public Result<Void> toggleFavorite(@PathVariable Long id,
                                      @RequestHeader("X-User-Id") Long userId) {
        literatureService.toggleFavorite(id, userId);
        return Result.success();
    }

    /**
     * 获取收藏文献列表
     */
    @PostMapping("/favorites")
    public Result<PageResult<LiteratureResponse>> getFavoriteList(@Valid @RequestBody LiteratureQueryRequest query,
                                                                 @RequestHeader("X-User-Id") Long userId) {
        PageResult<LiteratureResponse> result = literatureService.getFavoriteList(query, userId);
        return Result.success(result);
    }
    
    /**
     * 手动触发文献识别（管理员功能）
     */
    @PostMapping("/{id}/recognize")
    public Result<Void> triggerLiteratureRecognition(@PathVariable Long id,
                                                    @RequestHeader("X-User-Id") Long userId,
                                                    @RequestHeader("X-User-Type") Integer userType) {
        literatureService.triggerLiteratureRecognition(id, userId, userType);
        return Result.success();
    }
}